<template>
  <div>
    <Breadcrumb :style="{ margin: '15px 0' }">
      <BreadcrumbItem>首页</BreadcrumbItem>
      <BreadcrumbItem>订单管理</BreadcrumbItem>
      <BreadcrumbItem>团购订单</BreadcrumbItem>
    </Breadcrumb>
    <div class="page-refresh" @click="reloadPage">
      <Icon size="30" color="#9a9a9a" type="ios-refresh" /> 刷新
    </div>
    <Content class="layer-content">
      <Form inline>
        <FormItem>
          <Input
            style="width: 500px"
            v-model="keywords"
            search
            enter-button
            placeholder="请输入关键字"
            @on-search="searchGet"
            @submit.native.prevent />
        </FormItem>
        <FormItem>
          <Select style="width: 120px" placeholder="订单状态" clearable @on-change="selectStatus">
            <Option v-for="item in orderStatusArray" :value="item.id" :key="item.id">
              {{ item.name }}
            </Option>
          </Select>
        </FormItem>
        <FormItem>
          <Select style="width: 120px" placeholder="社团网点" clearable @on-change="selectSrvGroup">
            <Option v-for="item in srvGroups" :value="item.srvGroupId" :key="item.srvGroupId">
              {{ item.srvGroupName }}
            </Option>
          </Select>
        </FormItem>
        <FormItem>
          <DatePicker
            v-model="timeScopeModel"
            type="daterange"
            confirm
            placement="bottom-end"
            placeholder="选择订单日期范围"
            @on-ok="datePicker"
            style="width: 200px"></DatePicker>
        </FormItem>
        <FormItem>
          <Button @click="reset">重置</Button>
          <Button type="info" @click="exportOrder">导出</Button>
          <Button type="success" @click="batchDelivery">批量发货</Button>
        </FormItem>
      </Form>
      <Table border :columns="columns2" :data="dataGrid" @on-selection-change="Selector"></Table>
      <HigPager v-model="query" :total="count" :init="init"></HigPager>

      <Modal width="70%" v-model="showPrintVue" title="打印预览" :footer-hide="true">
        <PrintVue ref="refPrintView" :goodsItem="orderItem"></PrintVue>
      </Modal>
      <Modal v-model="modalDelivery" :footer-hide="true" title="一键发货" width="70%">
        <Delivery
          ref="refExpressView"
          :tableData="orderTable"
          :orderItem="orderItem"
          :callbank="eventAction"
          :key="keyIndex"></Delivery>
      </Modal>
      <Modal v-model="modalSelfDelivery" :footer-hide="true" title="一键发货" width="70%">
        <DeliverSelf
          ref="refExpressViewSelf"
          :callbank="eventAction"
          :key="keyIndex"></DeliverSelf>
      </Modal>
      <Modal v-model="modalDeliveryBatch" :footer-hide="true" title="批量发货" width="50%">
        <DeliverBatch
          ref="refExpressViewBatch"
          :callbank="eventAction"
          :key="keyIndex"></DeliverBatch>
      </Modal>
      <Modal v-model="modalDetail" :footer-hide="true" title="订单详情" width="80%">
        <Detail :dataGrid="orderTable" :orderItem="orderItem" :callbank="eventAction" :key="keyIndex"></Detail>
      </Modal>
      <Modal v-model="modalExpert" :footer-hide="true" title="订单导出" width="80%">
        <OrderExport ref="refExportView" :fileName="'团购订单'"></OrderExport>
      </Modal>
    </Content>
  </div>
</template>
<script>
import Detail from './detail.vue'
import Delivery from './delivery.vue'
import PrintVue from '../../print/purchase.vue'
import OrderExport from "./order-export.vue"
import DeliverSelf from './deliver-self.vue'
import DeliverBatch from './deliver-batch.vue'
export default {
  name: 'purchase',
  data() {
    return {
      timeScopeModel: [],
      batchSelector: [],
      keyIndex: 0,
      rowItem: {},
      showPrintVue: false,
      keywords: null,
      orderStatusArray: this.$dict.orderStatus.data,
      modalDelivery: false,
      modalSelfDelivery: false,
      modalDeliveryBatch: false,
      modalDetail: false,
      modalExpert: false,
      orderItem: {},
      orderTable: [],
      srvGroups: [],
      columns2: [
        {
          title: "序号",
          key: "shopOrderId",
          fixed: "left",
          width: 60,
          type: "selection",
        },
        {
          title: '客户姓名',
          key: 'custName',
          width: 120,
        },
        {
          title: '订单号',
          key: 'shopOrderId',
          width: 200,
        },
        {
          title: '网点',
          key: 'srvGroupName',
          minWidth: 200,
        },
        {
          title: '团长',
          key: 'holderName',
          width: 180,
        },
        {
          title: '联系电话',
          key: 'holderMobile',
          width: 180,
        },
        {
          title: '订单状态',
          key: 'orderStatus',
          width: 110,
          render: (h, params) => {
            return h('div', [
              h(
                'Tag',
                {
                  props: {
                    color: this.$dict.orderStatus.color(params.row.orderStatus),
                  },
                },
                this.$dict.orderStatus.name(params.row.orderStatus)
              ),
            ])
          },
        },
        {
          title: '订单数量',
          key: 'goodsTotalQty',
          width: 100,
        },
        {
          title: '交易金额(元)',
          key: 'orderActualAmt',
          width: 120,
          render: (h, params) => {
            return h('div', [
              h('a', { style: { fontSize: '12px', color: 'gray' } }, '￥'),

              h('span', params.row.orderActualAmt.toFixed(2)),
            ])
          },
        },
        {
          title: '退款金额(元)',
          key: 'refundAmt',
          width: 120,
          render: (h, params) => {
            return h('div', [
              h('a', { style: { fontSize: '12px', color: 'gray' } }, '￥'),

              h('span', params.row.refundAmt.toFixed(2)),
            ])
          },
        },
        {
          title: '结算金额(元)',
          key: 'settleAmt',
          width: 120,
          render: (h, params) => {
            return h('div', [
              h('a', { style: { fontSize: '12px', color: 'gray' } }, '￥'),

              h('span', params.row.settleAmt.toFixed(2)),
            ])
          },
        },
        {
          title: '创建时间',
          key: 'postTime',
          sortable: true,
          width: 150,
          render: (h, params) => {
            return h('div', [h('span', this.$date(params.row.postTime, 'yyyy-MM-dd HH:mm'))])
          },
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 120,
          render: (h, params) => {
            return h('Dropdown', { props: { transfer: true, trigger: 'click' } }, [
              h('a', [h('a', '下拉菜单'), h('Icon', { props: { type: 'ios-arrow-down' } })]),
              h('DropdownMenu', { slot: 'list' }, [
                h(
                  'DropdownItem',
                  {
                    nativeOn: {
                      click: () => {
                        this.openDetail(params.row)
                      },
                    },
                  },
                  '详情'
                ),
                h('DropdownItem',{nativeOn: {
                      click: () => {
                        this.offlineDelivery(params.row)
                      },
                    },props: { disabled: params.row.orderStatus !== 1 }},'发货'
                ),
                // h(
                //   'DropdownItem',
                //   {
                //     nativeOn: {
                //       click: () => {
                //         this.openDelivery(params.row)
                //       },
                //     },
                //     props: { disabled: params.row.orderStatus !== 1 },
                //   },
                //   '一键代发'
                // ),
                h(
                  'DropdownItem',
                  {
                    nativeOn: {
                      click: () => {
                        this.printView(params.row)
                      },
                    },
                  },
                  '打印'
                ),
              ]),
            ])
          },
        },
      ],
      count: 0,
      dataGrid: [],
      query: {
        pageIndex: 1,
        pageSize: 15,
        queryNeqs: [
          {
            field: 'order_status', //表域名1
            value: 9, //表域值
          },
        ],
        equal: {
          orderType: 5,
        },
      },
    }
  },
  created() {
    this.init()
    this.getSrvGroup()
  },
  components: {
    Detail,
    Delivery,
    PrintVue,
    OrderExport,
    DeliverSelf,
    DeliverBatch
  },
  methods: {
    reloadPage() {
      this.query.pageIndex = 1
      this.init()
    },
    eventAction() {
      this.modalDelivery = false
      this.modalDetail = false
      this.modalSelfDelivery = false
      this.modalDeliveryBatch = false
      this.keyIndex++
      this.init()
    },
    printView(item) {
      this.orderItem = item
      this.showPrintVue = true
      this.$refs.refPrintView.init(item.shopOrderId)
      this.$refs.refPrintView.orderAddr(item.pickSiteId)
    },
    //搜索
    searchGet() {
      let sqlLike = {
        fields: ['shop_order_id', 'cust_name'],
        keyword: this.keywords,
      }
      this.query.sqlLike = sqlLike
      this.query.pageIndex = 1
      this.init()
    },
    datePicker() {
      this.query.pageIndex = 1
      this.query.queryCompare = [
        {
          field: 'order_date',
          minValue: this.$date(this.timeScopeModel[0], 'yyyyMMdd'),
          maxValue: this.$date(this.timeScopeModel[1], 'yyyyMMdd'),
        },
      ]
      this.init()
    },
    //重置
    reset() {
      delete this.query.sqlLike
      delete this.query.equal.orderStatus
      delete this.query.queryCompare
      this.keywords = null
      this.query.pageIndex = 1
      this.timeScopeModel = []
      this.init()
    },
    selectStatus(status) {
      this.query.pageIndex = 1
      this.query.equal.orderStatus = status
      this.init()
    },
    selectSrvGroup(value) {
      this.query.pageIndex = 1
      this.query.equal.shopSrvGroupId = value
      this.init()
    },
    offlineDelivery(order) {
      if (order.orderStatus !== 1) {
        return false
      }
      this.modalSelfDelivery = true
      this.$refs.refExpressViewSelf.init(order)
    },
    openDelivery(order, id) {
      if (order.orderStatus !== 1) {
        return false
      }
      this.modalDelivery = true
      this.orderItem = order
      this.$refs.refExpressView.init()
      new this.$rest({
        gateway: 'agrobiz',
        service: 'agrobiz-order',
        url: '/v1.0/mall/goods/order/detail/page',
        query: {
          equal: {
            shopOrderId: order.shopOrderId,
          },
        },
        action: (res) => {
          if (res.data.code === 20000) {
            this.orderTable = res.data.data.list
          } else {
            this.$Notice.warning({
              title: '订单详情获取失败',
              desc: `失败原因：${res.data.msg}`,
            })
          }
        },
      }).get()
    },
    //查看详情
    openDetail(order, id) {
      this.modalDetail = true
      this.orderItem = order
      new this.$rest({
        gateway: 'agrobiz',
        service: 'agrobiz-order',
        url: '/v1.0/mall/goods/order/detail/page',
        query: {
          equal: {
            shopOrderId: order.shopOrderId,
          },
        },
        action: (res) => {
          if (res.data.code === 20000) {
            this.orderTable = res.data.data.list
          } else {
            this.$Message.error(res.data.msg)
          }
        },
      }).get()
    },
    getSrvGroup() {
      new this.$rest({
        gateway: 'agrobiz',
        service: 'agrobiz-uc',
        url: '/v1.0/srv/group/page',
        query: {
          equal: {
            auditStatus: 1,
          },
          pageIndex: 1,
          pageSize: 100,
        },
        action: (res) => {
          if (res.data.code === 20000) {
            this.srvGroups = res.data.data.list
          } else {
            this.$Message.error(res.data.msg)
          }
        },
      }).get()
    },
    //获取仓库门店订单，调用方包括供应商和前置仓库
    init() {
      this.query.equal.orgId = this.$store.getOrg('orgId')
      new this.$rest({
        gateway: 'agrobiz',
        service: 'agrobiz-order',
        url: '/v1.0/view/mall/order/info/page',
        query: this.query,
        action: (res) => {
          if (res.data.code === 20000) {
            this.dataGrid = res.data.data.list
            this.dataGrid.forEach((element) => {
              element.receiveModeText = element.receiveMode === 0 ? '自营' : '严选'
            })
            this.count = res.data.data.count
          } else {
            this.$Notice.warning({
              title: '获取失败',
              desc: `失败原因：${res.data.msg}`,
            })
          }
        },
      }).get()
    },
    Selector(selection) {
      this.batchSelector = selection
    },
    exportOrder() {
      this.modalExpert = true
      this.$refs.refExportView.init(this.query)
    },
    batchDelivery() {
      if (this.batchSelector.length === 0) {
        this.$Message.warning('请选择要发货的订单')
        return false
      }
      for (let i = 0; i < this.batchSelector.length; i++) {
        let order = this.batchSelector[i]
        if (order.orderStatus !== 1) {
          this.$Message.warning('请选择状态为待发货的订单')
          return false
        }
      }
      this.modalDeliveryBatch = true
      this.$refs.refExpressViewBatch.init(this.batchSelector)
    }
  },
}
</script>